#include "KVStateGRpc.h"

#include <grpcpp/server_builder.h>

#include <string>

#include "raft_utils/Config.h"

void KVStateGrpc::start(std::shared_ptr<raft::state_machine::StateMachine> state_machine) {
    grpc::EnableDefaultHealthCheckService(true);

    auto server_address = raft::utils::Config::getInstance()->get_state_machine_rpc_ip() + ":" +
                          std::to_string(raft::utils::Config::getInstance()->get_state_machine_rpc_port());
    grpc::ServerBuilder builder;
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    builder.RegisterService(state_machine.get());
    server_ = builder.BuildAndStart();
    server_->Wait();
}

void KVStateGrpc::stop() {
    if (server_) {
        server_->Shutdown();
    }
}